<?php

namespace Admin;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Utility\Session\Session;

class Module {

    /**
     * @param \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return void
     */
    public function onBootstrap(MvcEvent $e) {

        $eventManager = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
        //后台 Session 验证拦截, 当 Session 验证失败时 跳转至member 进行登录
        $eventManager->attach(MvcEvent::EVENT_DISPATCH, function(MvcEvent $s) {
            // $s->getTarget()->filter 所有 controller 中是否设置 filter 成员变量
            //echo $s->getTarget()->filter;
            if (@$s->getTarget()->filter) {
                $session = new Session();
                if (!$session->userid) {
                    //跳转至member 进行登录
                    $oldurl = $s->getRequest()->getUri()->getPath();
                    $url = $s->getRouter()->assemble(array('controller' => 'index', 'action' => 'index'), array('name' => 'member/child'));
                    $response = $s->getResponse();
                    $response->getHeaders()->addHeaderLine('Location', $url . "?referer=" . urlencode($oldurl));
                    $response->setStatusCode(302);
                    return $response;
                }
            }
        }
        );
        // 注册一个事件
        $application = $e->getParam('application');
        $application->getEventManager()->attach('dispatch', array($this, 'setLayout'));
    }

    /**
     * @param  \Zend\Mvc\MvcEvent $mvcEvent The MvcEvent instance
     * @return void
     */
    public function setLayout($mvcEvent) {
        $matches = $mvcEvent->getRouteMatch();
        /**
         * @var \Zend\Mvc\Controller\AbstractActionController; $controller
         */
        $controller = $matches->getParam('controller');
        if (false === strpos($controller, __NAMESPACE__)) {
            // not a controller from this module
            return false;
        }
        // 自定义设置布局模板
        //针对 module.confi.php 下 template_map => layout 的设置
        $viewModel = $mvcEvent->getViewModel();
        if (!$viewModel->terminate()) {
            $viewModel->setTemplate('admin/layout');
        };
    }

    public function getConfig() {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig() {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

}
